package com.kuaimacode.kframework.admin.services.agent;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.constants.SysAgentUserPasswordConstants;
import com.kuaimacode.kframework.mybatis.mapper.agent.SysAgentMapUserRoleMapper;
import com.kuaimacode.kframework.mybatis.mapper.agent.SysAgentUserMapper;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgentMapUserRole;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgentUser;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.security.SecureRandom;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@Service
public class SysAgentUserService extends ServiceImpl<SysAgentUserMapper, SysAgentUser> {


	@Autowired
	private SysAgentMapUserRoleMapper sysMapUserRoleMapper;

	/**
	 * 根据用户名查找用户
	 *
	 * @param userName 用户名
	 * @return
	 */
	public SysAgentUser findByUserName(String userName) {
		return baseMapper.findByUserName(userName);
	}

	public SysAgentUser findByUserNameAgentId(String username, String agentId) {
	    QueryWrapper<SysAgentUser> wrapper = new QueryWrapper<>();
	    wrapper.eq("user_name", username);
	    wrapper.eq("agent_id", agentId);
	    return baseMapper.selectOne(wrapper);
    }

	/**
	 *  分页查找所有的用户
	 * @param pageNum 当前页码，从1开始
	 * @param pageSize  一页显示多少行
	 * @return
	 */
	public PageInfo<SysAgentUser> findAll(int pageNum, int pageSize, SysAgentUser searchUser) {
		PageHelper.startPage(pageNum, pageSize);
		QueryWrapper<SysAgentUser> wrapper = new QueryWrapper<>();
		if (StringUtils.isNotBlank(searchUser.getUserName())) {
		    wrapper.like("user_name", searchUser.getUserName());
        }
		if (StringUtils.isNotBlank(searchUser.getCellphone())) {
		    wrapper.like("cellphone", searchUser.getCellphone());
        }
		List<SysAgentUser> users = baseMapper.selectList(wrapper);
		/*List<SysAgent> agentList = agentService.list();
        Optional.ofNullable(users)
                .ifPresent(sysAgentUsers ->
                        sysAgentUsers.forEach(sysAgentUser -> {
                                    Optional<SysAgent> sysAgent = agentList.stream().filter(agent -> sysAgentUser.getAgentId().equals(agent.getId())).findFirst();
                                    sysAgent.ifPresent(agent -> sysAgentUser.set);
                                }

                        ));*/
		return new PageInfo<>(users);
	}

    /**
     * 查询分站下的用户列表
     * @param pageNum
     * @param pageSize
     * @param agentId
     * @return
     */
    public PageInfo<SysAgentUser> findByAgentId(int pageNum, int pageSize, String agentId) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<SysAgentUser> wrapper = new QueryWrapper<>();
        wrapper.eq("agent_id", agentId);
        List<SysAgentUser> users = baseMapper.selectList(wrapper);
        return new PageInfo<>(users);
    }

	/**
	 * 分配角色
	 * @param id 用户id
	 * @param roleIds 角色id
	 */
	@Transactional(rollbackFor = Exception.class)
	public void grant(String id, String[] roleIds) {
	    //删除已关联的角色
        QueryWrapper<SysAgentMapUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        sysMapUserRoleMapper.delete(wrapper);
		sysMapUserRoleMapper.grant(id, roleIds);
	}

    /**
     * 重置密码
     * @param userId
     */
	public void resetPassword(Long userId) {
	    SysAgentUser agentUser = new SysAgentUser();
	    agentUser.setUserId(userId);
        // 生成随机salt
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[16];
        random.nextBytes(bytes);
        String salt = Base64.encodeBase64String(bytes);
        agentUser.setSalt(salt);
        // 加密密码
        String passwordEncrypt = new SimpleHash(SysAgentUserPasswordConstants.HASHALGORITHM_NAME, SysAgentUserPasswordConstants.DEFAULT_PASSWORD,
                salt, SysAgentUserPasswordConstants.HASHITERATIONS).toString();
        agentUser.setPassword(passwordEncrypt);
        updateById(agentUser);
    }

	/**
	 * 修改用户密码
	 *
	 * @param user
	 * @param oldPassword
	 * @param password1
	 * @param password2
	 */
	public void updatePwd(SysAgentUser user, String oldPassword, String password1, String password2) {
		Assert.notNull(user, "用户不能为空");
		Assert.notNull(oldPassword, "原始密码不能为空");
		Assert.notNull(password1, "新密码不能为空");
		Assert.notNull(password2, "重复密码不能为空");

		SysAgentUser dbUser = baseMapper.findByUserName(user.getUserName());
		Assert.notNull(dbUser, "用户不存在");

		String salt = dbUser.getSalt();
		// 旧密码加密后与数据库中的原密码比较是否一致
		String oldPasswordEncrypt = new SimpleHash(SysAgentUserPasswordConstants.HASHALGORITHM_NAME, oldPassword,
				salt, SysAgentUserPasswordConstants.HASHITERATIONS).toString();
		Assert.isTrue(user.getPassword().equals(oldPasswordEncrypt), "原始密码不正确");
		Assert.isTrue(password1.equals(password2), "两次密码不一致");
		String password1Encrypt = new SimpleHash(SysAgentUserPasswordConstants.HASHALGORITHM_NAME, password1,
				salt, SysAgentUserPasswordConstants.HASHITERATIONS).toString();
		dbUser.setPassword(password1Encrypt);
		baseMapper.updateById(dbUser);
	}

	/**
	 * 根据用户id查找roleIds
	 *
	 * @param userId 用户id
	 * @return
	 */
	public List<String> findRoleIdsByUserId(String userId) {
		return sysMapUserRoleMapper.findRoleIdsByUserId(userId);
	}

	/**
	 * 新建保存用户，自动生成salt盐，加密password保存
	 * @param user
	 * @return 
	 */
    @Transactional(rollbackFor = Exception.class)
	public boolean save(SysAgentUser user, List<String> roleIds) {
		if (null != user) {
			String password = user.getPassword();
			user.setUserId(null);

			// 生成随机salt
			SecureRandom random = new SecureRandom();
			byte bytes[] = new byte[16];
			random.nextBytes(bytes);
			String salt = Base64.encodeBase64String(bytes);
			user.setSalt(salt);

			// 加密密码
			String passwordEncrypt = new SimpleHash(SysAgentUserPasswordConstants.HASHALGORITHM_NAME, password,
					salt, SysAgentUserPasswordConstants.HASHITERATIONS).toString();
			user.setPassword(passwordEncrypt);
			int flag = baseMapper.insert(user);

			if (CollectionUtils.isNotEmpty(roleIds)) {
                roleIds.stream().map(roleId -> {
                    SysAgentMapUserRole userRole = new SysAgentMapUserRole();
                    userRole.setRoleId(Long.parseLong(roleId));
                    userRole.setUserId(user.getUserId());
                    return userRole;
                }).collect(Collectors.toList()).forEach(userRole -> sysMapUserRoleMapper.insert(userRole));
            }

			return flag > 0;
		}
		return false;
	}

	@Transactional(rollbackFor = Exception.class)
	public boolean updateById(SysAgentUser agentUser, List<String> roleIds) {
        if (CollectionUtils.isNotEmpty(roleIds)) {
            QueryWrapper<SysAgentMapUserRole> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("user_id", agentUser.getUserId());
            sysMapUserRoleMapper.delete(deleteWrapper);

            roleIds.stream().map(roleId -> {
                SysAgentMapUserRole userRole = new SysAgentMapUserRole();
                userRole.setRoleId(Long.parseLong(roleId));
                userRole.setUserId(agentUser.getUserId());
                return userRole;
            }).collect(Collectors.toList()).forEach(userRole -> sysMapUserRoleMapper.insert(userRole));
        }
        return this.updateById(agentUser);
    }
}

